import React, { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Input,
  Select,
  Space,
  Button,
  Tag,
  Typography,
  Card,
  Row,
  Col,
  Statistic,
  message,
  Popconfirm,
} from 'antd';
import {
  SearchOutlined,
  DownloadOutlined,
  FireOutlined,
  CloudDownloadOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getTorrents, downloadTorrent, deleteTorrent } from '../../api/torrent';
import { Torrent, PageResult } from '../../types';
import { formatBytes, formatDateTime } from '../../utils/format';
import { useAuth } from '../../context/AuthContext';
import { getDailyDownloadLimit } from '../../api/user';
import { useApiState } from '../../hooks/useApiState';
import { usePagination } from '../../hooks/usePagination';
import { useErrorHandler } from '../../hooks/useErrorHandler';
import { getPromotionTag } from '../../utils/common';
import { TORRENT_CATEGORIES } from '../../constants';

const { Search } = Input;
const { Option } = Select;
const { Text } = Typography;

const TorrentList: React.FC = () => {
  const { user } = useAuth();
  const { handleError } = useErrorHandler();

  // 使用自定义Hooks管理状态
  const torrentState = useApiState<Torrent[]>({ initialData: [] });
  const { pagination, getTablePaginationConfig, updatePagination } = usePagination();

  const [dailyDownloadLimit, setDailyDownloadLimit] = useState<number>(0);
  const [filters, setFilters] = useState({
    keyword: '',
    category: '',
  });



  useEffect(() => {
    fetchTorrents();
    if (user) {
      fetchDailyDownloadLimit();
    }
  }, [fetchTorrents, fetchDailyDownloadLimit, user]);

  // 添加事件监听器
  useEffect(() => {
    const handleUpdateLimit = () => {
      if (user) {
        fetchDailyDownloadLimit();
      }
    };
    
    window.addEventListener('updateDailyDownloadLimit', handleUpdateLimit);
    
    return () => {
      window.removeEventListener('updateDailyDownloadLimit', handleUpdateLimit);
    };
  }, [user]);

  const fetchTorrents = useCallback(async () => {
    await torrentState.execute(
      () => getTorrents({
        page: pagination.current,
        size: pagination.pageSize,
        category: filters.category || undefined,
        keyword: filters.keyword || undefined,
      }),
      {
        onSuccess: (response) => {
          if (response.code === 200) {
            updatePagination({ total: response.data.total });
          }
        },
        transform: (response) => response.data.records,
      }
    );
  }, [pagination.current, pagination.pageSize, filters, torrentState, updatePagination]);

  const fetchDailyDownloadLimit = useCallback(async () => {
    try {
      const response = await getDailyDownloadLimit();
      if (response.code === 200) {
        setDailyDownloadLimit(response.data);
      }
    } catch (error) {
      handleError(error, {
        showMessage: false, // 不显示错误消息，因为这不是关键功能
        defaultMessage: '获取每日下载限制失败'
      });
    }
  }, [handleError]);

  const handleDownload = useCallback(async (torrentId: number) => {
    try {
      const response = await downloadTorrent(torrentId);

      // 创建下载链接
      const blob = new Blob([response], { type: 'application/x-bittorrent' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `torrent_${torrentId}.torrent`;
      document.body.appendChild(link);
      link.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);

      message.success('种子文件下载成功');

      // 更新下载限制
      await fetchDailyDownloadLimit();
    } catch (error) {
      handleError(error, { defaultMessage: '下载种子失败' });
      // 即使下载失败也要更新限制，可能是达到限制导致的
      await fetchDailyDownloadLimit();
    }
  }, [fetchDailyDownloadLimit, handleError]);

  const handleDelete = useCallback(async (torrentId: number) => {
    try {
      await deleteTorrent(torrentId);
      message.success('种子删除成功');
      await fetchTorrents(); // 刷新列表
    } catch (error) {
      handleError(error, { defaultMessage: '删除种子失败' });
    }
  }, [fetchTorrents, handleError]);

  // 检查是否有删除权限
  const canDelete = (torrent: Torrent) => {
    if (!user) return false;
    // 管理员（等级4）或种子上传者可以删除
    return user.userClass >= 4 || torrent.uploaderId === user.id;
  };



  const columns = [
    {
      title: '种子信息',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record: Torrent) => (
        <div>
          <Link to={`/torrents/${record.id}`}>
            <Text strong>{title}</Text>
          </Link>
          <div style={{ marginTop: 4 }}>
            <Space split={<span>•</span>}>
              <Tag color="blue">{record.category}</Tag>
              {record.promotionStatus !== undefined && getPromotionTag(record.promotionStatus)}
              <Text type="secondary">
                上传者: {record.uploader || record.uploaderName}
              </Text>
            </Space>
          </div>
        </div>
      ),
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 100,
      render: (size: number) => formatBytes(size || 0),
    },
    {
      title: '做种/下载',
      key: 'peers',
      width: 120,
      render: (record: Torrent) => (
        <Space direction="vertical" size="small">
          <Text type="success">↑ {record.seeders}</Text>
          <Text type="warning">↓ {record.leechers}</Text>
        </Space>
      ),
    },
    {
      title: '完成',
      dataIndex: 'finished',
      key: 'finished',
      width: 80,
      render: (finished: number, record: Torrent) => (
        <Text>{finished || record.completedCount || 0}</Text>
      ),
    },
    {
      title: '上传时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: 150,
      render: (time: string, record: Torrent) => 
        formatDateTime(time || record.uploadedAt || ''),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (record: Torrent) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record.id)}
          >
            下载
          </Button>
          {canDelete(record) && (
            <Popconfirm
              title="确定要删除这个种子吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="primary"
                size="small"
                icon={<DeleteOutlined />}
                danger
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="种子总数"
              value={pagination.total}
              prefix={<CloudDownloadOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃种子"
              value={torrentState.data?.filter(t => t.seeders > 0).length || 0}
              prefix={<FireOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日剩余下载"
              value={dailyDownloadLimit === -1 ? '无限制' : dailyDownloadLimit}
              prefix={<DownloadOutlined />}
              valueStyle={{ color: dailyDownloadLimit === -1 ? '#52c41a' : '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <Row gutter={16} align="middle">
            <Col span={8}>
              <Search
                placeholder="搜索种子标题..."
                allowClear
                enterButton={<SearchOutlined />}
                value={filters.keyword}
                onChange={(e) => setFilters(prev => ({ ...prev, keyword: e.target.value }))}
                onSearch={() => {
                  setPagination(prev => ({ ...prev, current: 1 }));
                  fetchTorrents();
                }}
              />
            </Col>
            <Col span={6}>
              <Select
                style={{ width: '100%' }}
                placeholder="选择分类"
                value={filters.category}
                onChange={(value) => setFilters(prev => ({ ...prev, category: value }))}
              >
                {TORRENT_CATEGORIES.map(cat => (
                  <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              <Button type="primary" block onClick={fetchTorrents}>
                刷新
              </Button>
            </Col>
            <Col span={6}>
              <Link to="/upload">
                <Button type="primary" block>
                  上传种子
                </Button>
              </Link>
            </Col>
          </Row>

          <Table
            columns={columns}
            dataSource={torrentState.data || []}
            rowKey="id"
            loading={torrentState.loading}
            pagination={getTablePaginationConfig()}
          />
        </Space>
      </Card>
    </div>
  );
};

export default TorrentList; 